﻿using Prism.Commands;
using System.Linq;
using Xcj.Mes.WholeLine.DataBase.Entity;
using Xcj.Mes.WholeLine.DataBase.Service;

namespace Xcj.Mes.WholeLine.ZH.HG.Shell.ViewModels.Config
{
    public class DeviceViewModel : BaseViewModel
    {
        public DeviceConfigEntity deviceConfigEntity
        {
            get => App.deviceConfigEntity;
            set
            {
                App.deviceConfigEntity = value;
                RaisePropertyChanged();
            }
        }
        
        // 声明一个DelegateCommand
        public DelegateCommand SaveCommand { get; private set; }

        public DeviceViewModel()
        {
            using(DeviceConfigService service =  new DeviceConfigService())
            {
                deviceConfigEntity = service?.All()?.OrderByDescending(o => o.CreateTime)?.FirstOrDefault();
                if(deviceConfigEntity == null) deviceConfigEntity = new DeviceConfigEntity();
            }

            // 初始化命令，并关联执行方法
            SaveCommand = new DelegateCommand(OnSave);
        }

        private void OnSave()
        {
            // 这里写点击按钮后要执行的逻辑

            using (DeviceConfigService service = new DeviceConfigService())
            {
                DeviceConfigEntity _deviceConfigEntity = service?.All()?.OrderByDescending(o => o.CreateTime)?.FirstOrDefault();
                if( _deviceConfigEntity == null)
                {
                    _deviceConfigEntity = deviceConfigEntity;
                    service.Add(_deviceConfigEntity);
                }
                else
                {
                    _deviceConfigEntity.CreateTime = System.DateTime.Now;
                    _deviceConfigEntity.DeviceSn = deviceConfigEntity.DeviceSn;
                    _deviceConfigEntity.HostName = deviceConfigEntity.HostName;
                    _deviceConfigEntity.HostIP   = deviceConfigEntity.HostIP;
                    _deviceConfigEntity.HostPort = deviceConfigEntity.HostPort;
                    _deviceConfigEntity.DataBaseServerIP   = deviceConfigEntity.DataBaseServerIP;
                    _deviceConfigEntity.DataBaseServerPort = deviceConfigEntity.DataBaseServerPort;
                    _deviceConfigEntity.DataBaseName       = deviceConfigEntity.DataBaseName;
                    _deviceConfigEntity.DataBaseAccount    = deviceConfigEntity.DataBaseAccount;
                    _deviceConfigEntity.DataBasePassword   = deviceConfigEntity.DataBasePassword;
                    _deviceConfigEntity.ReportFormsFolder  = deviceConfigEntity.ReportFormsFolder;
                    service.Edit(_deviceConfigEntity);
                }
            }
        }
    }
}
